using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace CHot
{
    [CustomEditor(typeof(ColliderGroup))]
    public class ColliderGroupEditor : Editor
    {
        ColliderGroup colliderGroup;

        void OnEnable()
        {
            colliderGroup = (ColliderGroup)target;
            SavePrefab();
        }

        public override void OnInspectorGUI()
        {
            if (GUILayout.Button("刷新并保存"))
            {
                SavePrefab();
            }
            base.OnInspectorGUI();
        }

        public void SavePrefab()
        {
            //删除Unity的组件
            CircleCollider2D[] unityColliders = colliderGroup.gameObject.GetComponentsInChildren<CircleCollider2D>();
            for (int i = 0; i < unityColliders.Length; i++)
            {
                DestroyImmediate(unityColliders[i]);
            }
            Rigidbody2D[] rigidbody2Ds = colliderGroup.gameObject.GetComponentsInChildren<Rigidbody2D>();
            for (int i = 0; i < rigidbody2Ds.Length; i++)
            {
                DestroyImmediate(rigidbody2Ds[i]);
            }

            //加自定义组件
            Collider[] colliders = colliderGroup.GetComponentsInChildren<Collider>();
            
            //检查多余的删掉
            List<GameObject> exists = new List<GameObject>();
            for (int i = 0; i < colliders.Length; i++)
            {
                Collider collider = colliders[i];
                if (!exists.Contains(collider.gameObject))
                {
                    exists.Add(collider.gameObject);
                }
                else
                {
                    DestroyImmediate(collider);
                }
            }

            //限制鱼只能使用CircleCollider,不能使用BoxCollider
            if (colliderGroup.isFish)
            {
                for (int i = 0; i < colliders.Length; i++)
                {
                    if(colliders[i] as BoxCollider)
                    {
                        EditorUtility.DisplayDialog("提示", "鱼碰撞只能使用 CircleCollider", "确定");
                        return;
                    }
                }
            }

            colliderGroup.colliders = colliders;

            //开始保存
            bool isInstance = PrefabUtility.IsPartOfPrefabInstance(colliderGroup.gameObject);
            if (isInstance)
            {
                //在外部场景里操作，执行保存
                GameObject prefab = PrefabUtility.GetCorrespondingObjectFromSource(colliderGroup.gameObject);
                string prefabPath = AssetDatabase.GetAssetPath(prefab);
                GameObject newPrefab = GameObject.Instantiate(colliderGroup.gameObject);
                PrefabUtility.SaveAsPrefabAsset(newPrefab, prefabPath);
                AssetDatabase.SaveAssets();
                GameObject.DestroyImmediate(newPrefab);
            }
            else
            {
                EditorUtility.SetDirty(target);
            }
        }
    }
}